package com.ruoyi.common.utils.poi;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;

/**
 * Excel相关处理
 * 
 * @author ruoyi
 */
public class MyBaseEasyExcelUtil<T>
{
	  
	  /**
     * 实体对象
     */
	private Class<T> clazz;

	private String excelName;
    
    private FileOutputStream outputStream;
    
    private ExcelWriter excelWriter;
    
    private int sheetDataSize = 0;

    private int sheetNo = 0;


    
    public MyBaseEasyExcelUtil(Class<T> clazz,String excelName,String exportPath) throws FileNotFoundException{
    	this.excelName = excelName;
    	this.clazz = clazz;
    	outputStream = new FileOutputStream(exportPath + excelName + ".xlsx");
        excelWriter = EasyExcel.write(outputStream).build();
    }
    
	public void writeList(Collection<T> openList) {
		 if(openList==null || openList.size() == 0) {
			 return;
		 }
		 sheetDataSize += openList.size();
         if(sheetDataSize > 1000000){
            sheetNo++;
            sheetDataSize = openList.size();
         }
		 WriteSheet writeSheet = EasyExcel.writerSheet(sheetNo, excelName+"-"+sheetNo).head(clazz)
				 .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
		 excelWriter.write(openList, writeSheet);
	}
	
	public void finish() throws IOException {
		excelWriter.finish();
	    outputStream.flush();
	}
	
	public void finallyClose() {
	   if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
	}

	
	 
	 
}
